package com.xr.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 项目启动时，注入ApplicationContext
 */
public class SpringContextHolder implements ApplicationContextAware {

  private static ApplicationContext applicationContext = null;

  private static Logger logger = LoggerFactory.getLogger(SpringContextHolder.class);

  public void setApplicationContext(ApplicationContext applicationContext) {
    logger.debug("注入ApplicationContext到SpringContextHolder:" + applicationContext);

    if (SpringContextHolder.applicationContext != null) {
      logger.warn("SpringContextHolder中的ApplicationContext被覆盖,原有Context为:" + SpringContextHolder.applicationContext);
    }

    SpringContextHolder.applicationContext = applicationContext;
  }

  /**
   * 取得存储在静态变量中的ApplicationContext.
   */
  public static ApplicationContext getApplicationContext() {
    checkApplicationContext();
    return applicationContext;
  }

  /**
   * 根据bean name获取bean instance
   * @param name
   * @param <T>
   * @return
   */
  public static <T> T getBean(String name) {
    checkApplicationContext();
    return (T) applicationContext.getBean(name);
  }

  /**
   * 根据bean Class获取bean instance
   * @param clazz
   * @param <T>
   * @return
   */
  public <T> T getBean(Class<T> clazz){
    return applicationContext.getBean(clazz);
  }

  private static void checkApplicationContext() {
    if (null == applicationContext) {
      throw new IllegalStateException("ApplicationContext未注入");
    }
  }
}
